/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.tukano.odt;

import it.tukano.text.StringScanner;

/**
 *
 * @author utente4
 */
public class OdtParagraph {
    
    public static int getElementEndIndex(String parEnd, String xml, String token) {
        int tokenIndex = xml.indexOf(token);
        int paragraphEnd = xml.indexOf(parEnd, tokenIndex) + parEnd.length();
        return paragraphEnd;
    }
    
    public static int getElementStartIndex(String parStart, String xml, String token) {
        int tokenIndex = xml.indexOf(token);
        int paragraphStart = StringScanner.backIndexOf(xml, parStart, tokenIndex);
        return paragraphStart;
    }
    
    public static int getParagraphStartIndex(String xml, String token) {
        String parStart = "<text:p";
        return getElementStartIndex(parStart, xml, token);
    }
    
    public static int getParagraphEndIndex(String xml, String token) {
        String parEnd = "</text:p>";
        return getElementEndIndex(parEnd, xml, token);
    }    
    
    public static String deleteParagraph(String xml, String tokenInParagraph) {
        for (int i = getParagraphStartIndex(xml, tokenInParagraph); i >= 0; i = getParagraphStartIndex(xml, tokenInParagraph)) {
            int e = getParagraphEndIndex(xml, tokenInParagraph);
            xml = xml.substring(0, i) + xml.substring(e, xml.length());
        }
        return xml;
    }
    
    private final String sourceParagraph;
    private String newParagraph;
    private final String lineStart;
    private final String lineEnd = "</text:p>";

    public OdtParagraph(String text) {
        this.sourceParagraph = text;
        
        int hend = text.indexOf("\">") + 2;
        lineStart = text.substring(0, hend);
        newParagraph = sourceParagraph;
    }
    
    public void remove(String token) {
        newParagraph = newParagraph.replace(token, "");
    }

    public void appendClonedParagraph(String paragraphContent) {
        newParagraph += lineStart + paragraphContent + lineEnd;
    }
    
    public String apply(String xml) {
        return xml.replace(sourceParagraph, newParagraph);
    }
}
